import hashlib
import logging
import time
import json
import requests
from controllers.config import *
from flask import make_response, send_from_directory, jsonify
import os
from controllers.aws_db import S3Operation
from copy import deepcopy

s3_client = S3Operation()

def fomat_timestamp(secs, format="%Y-%m-%d %H:%M:%S"):
    localtime = time.localtime(secs)
    format_time = time.strftime(format, localtime)
    return format_time

def fomat_date_str(secs):
    timeArray = time.strptime(secs, "%Y-%m-%d %H:%M:%S")
    timeStamp = int(time.mktime(timeArray))
    return timeStamp


def ToInt(value):
    return int(float(value))


def ToSidList(str_sid):
    data = []
    if str(str_sid) == '-1':
        return [-1]
    sid_list = str_sid.split(',')
    for i in range(len(sid_list)):
        sid_str = str(sid_list[i])
        if sid_str == '':
            continue
        if '-' in sid_str and str(sid_str) != '-1':
            tmp_sid = sid_str.split('-')
            for j in range(int(tmp_sid[0]),int(tmp_sid[1])+1):
                data.append(j)
        else:
            data.append(int(sid_str))
    return data


def push_to_env(filename):
    filename = filename + '.json'
    data = {
        "project": PROJECT_NAME,
        "env": EVN,
        "filename": filename,
        "token": "from_yunying"
    }
    r = requests.post(SEND_URL,json=data)
    print(r.status_code)
    return True


def RewardToDic(reward_list, item_pos=0, reward_item_list = []):

    if len(reward_item_list) == 0:
        reward_item_list = rewardList()
        reward_item_list = reward_item_list['name']

    result_bonus = {}
    if len(reward_list) > 0:
        for x in range(len(reward_list)):
            item_type = reward_list[x]['a'][0]
            item_id = reward_list[x]['a'][1]
            item_num = reward_list[x]['a'][2]
            item_price = 100
            if item_type in reward_item_list and str(item_id) in reward_item_list[item_type]:
                item_name = reward_item_list[item_type][str(item_id)]
            else:
                item_name = 'ERROR'
            tmp = {"type": item_type, "id": item_id, "num": item_num,
                   "price": item_price, "pos": item_pos, "name": item_name}
            if item_pos not in result_bonus:
                result_bonus[item_pos] = {}
                result_bonus[item_pos]['reward'] = []
            result_bonus[item_pos]['reward'].append(tmp)
    else:
        if item_pos not in result_bonus:
            result_bonus[item_pos] = {}
            result_bonus[item_pos]['reward'] = []

    return result_bonus


def rewardList():
    equip_data = loadEquip()
    doc_data = loadDocument()
    game_data = loadGame()
    sub_game_data = loadSubGame()
    # sub_doc_data = loadSubDoc()

    result_data = {}
    item_name_list = {}
    # gem
    result_data[1] = [{"value": "gem", "id": 0, "price": 1}]
    if 1 not in item_name_list:
        item_name_list[1] = {}
    item_name_list[1]['0'] = 'gem'

    # gem
    result_data[110] = [{"value": "resource_chest", "id": 0, "price": 1}]
    if 110 not in item_name_list:
        item_name_list[110] = {}
    item_name_list[110]['0'] = 'resource_chest'

    result_data[104] = [{"value": "battle_pass_exp", "id": 0, "price": 1}]
    if 104 not in item_name_list:
        item_name_list[104] = {}
    item_name_list[104]['0'] = 'battle_pass_exp'
    # 联盟Loylty
    result_data[27] = [{"value": "Loylty", "id": 0, "price": 1}]
    if 27 not in item_name_list:
        item_name_list[27] = {}
    item_name_list[27]['0'] = 'Loylty'
    # 强化石
    result_data[71] = [{"value": "强化石", "id": 0, "price": 1}]
    if 71 not in item_name_list:
        item_name_list[71] = {}
    item_name_list[71]['0'] = '强化石'
    # 卡牌经验
    result_data[74] = [{"value": "card_exp", "id": 0, "price": 1}]
    if 74 not in item_name_list:
        item_name_list[74] = {}
    item_name_list[74]['0'] = 'card_exp'
    # 付费点券
    result_data[179] = [{"value": "付费点券", "id": 0, "price": 1}]
    if 179 not in item_name_list:
        item_name_list[179] = {}
    item_name_list[179]['0'] = '付费点券'
    # 道具
    result_data[0] = []
    for i in game_data['game_item']:
        if i in doc_data['doc_item']:
            name = doc_data['doc_item'][str(i)]['name']
        else:
            name = '活动文案不存在'
        price = int(game_data['game_item'][i]['a0'])
        tmp = {}
        tmp['value'] = name + '-' + str(i)
        tmp['id'] = int(i)
        tmp['price'] = price
        result_data[0].append(tmp)

        if 0 not in item_name_list:
            item_name_list[0] = {}
        item_name_list[0][i] = name + '-' + str(i)

    for i in sub_game_data['sub_game_item']:
        if i in doc_data['doc_item']:
            name = doc_data['doc_item'][str(i)]['name']
        else:
            name = '活动文案不存在'
        price = 1000
        tmp = {}
        tmp['value'] = name + '-' + str(i)
        tmp['id'] = int(i)
        tmp['price'] = price
        result_data[0].append(tmp)
        item_name_list[0][i] = name + '-' + str(i)
    # 兑换币
    result_data[117] = []
    for i in sub_game_data['sub_game_token']:
        if i in doc_data['doc_exchange_token']:
            name = doc_data['doc_exchange_token'][str(i)]['name']
        else:
            name = '活动文案不存在'
        price = 1000
        tmp = {}
        tmp['value'] = name + '-' + str(i)
        tmp['id'] = int(i)
        tmp['price'] = price
        result_data[117].append(tmp)

        if 117 not in item_name_list:
            item_name_list[117] = {}

        item_name_list[117][i] = name + '-' + str(i)

    # al_gift
    result_data[10] = []
    for i in game_data['game_al_gift_pack']:
        if i in doc_data['doc_alliance_gift_new']:
            name = doc_data['doc_alliance_gift_new'][str(i)]['name']
        else:
            name = '活动文案不存在'
        price = 100
        tmp = {}
        tmp['value'] = name + '-' + str(i)
        tmp['id'] = int(i)
        tmp['price'] = price
        result_data[10].append(tmp)

        if 10 not in item_name_list:
            item_name_list[10] = {}

        item_name_list[10][i] = name + '-' + str(i)
    # equipment
    result_data[23] = []
    for i in equip_data['equip_equipment']:
        if i in doc_data['doc_equipment']:
            name = doc_data['doc_equipment'][str(i)]['name']
        else:
            name = '活动文案不存在'
        price = 100
        for lv in range(1, 7):
            tmp = {}
            equip_id = int(i) * 10 + lv
            tmp['value'] = "Lv." + str(lv) + " " + name
            tmp['id'] = int(equip_id)
            tmp['price'] = price
            result_data[23].append(tmp)
            if 23 not in item_name_list:
                item_name_list[23] = {}

            item_name_list[23][i] = "Lv." + str(lv) + " " + name

    # equipment_crystal
    result_data[24] = []
    for i in equip_data['equip_crystal']:
        _type = str(int(int(i)/10))
        _lv = int(int(i) % 10)
        if _type in doc_data['doc_equipment_crystal']:
            name = doc_data['doc_equipment_crystal'][_type]['name']
        else:
            name = '活动文案不存在'
        price = 100
        tmp = {}
        tmp['value'] = "Lv." + str(_lv) + " " + name
        tmp['id'] = int(i)
        tmp['price'] = price
        result_data[24].append(tmp)
        if 24 not in item_name_list:
            item_name_list[24] = {}
        item_name_list[24][i] = "Lv." + str(_lv) + " " + name

    # equipment_material
    result_data[25] = []
    for i in equip_data['equip_material']:
        _type = str(int(int(i)/10))
        _lv = int(int(i) % 10)
        if _type in doc_data['doc_equipment_material']:
            name = doc_data['doc_equipment_material'][str(_type)]['name']
        else:
            name = '活动文案不存在'
        price = int(equip_data['equip_material'][i]['b'][6])
        tmp = {}
        tmp['value'] = "Lv." + str(_lv) + " " + name
        tmp['id'] = int(i)
        tmp['price'] = price

        result_data[25].append(tmp)
        if 25 not in item_name_list:
            item_name_list[25] = {}
        item_name_list[25][i] = "Lv." + str(_lv) + " " + name

    # equip_soul
    result_data[32] = []
    for i in equip_data['equip_soul']:
        _type = str(int(int(i)/10))
        _lv = int(int(i) % 10)
        if _type in doc_data['doc_equipment_soul']:
            name = doc_data['doc_equipment_soul'][str(_type)]['name']
        else:
            name = '活动文案不存在'
        price = 100
        tmp = {}
        tmp['value'] = "Lv." + str(_lv) + " " + name
        tmp['id'] = int(i)
        tmp['price'] = price
        result_data[32].append(tmp)
        if 32 not in item_name_list:
            item_name_list[32] = {}
        item_name_list[32][i] = "Lv." + str(_lv) + " " + name

    # equip_parts
    result_data[33] = []
    for key,value in equip_data['equip_parts'].items():
        _type = str(value['b'][0])
        _lv = int(value['b'][1])
        if _type in doc_data['doc_equipment_fragment']:
            name = doc_data['doc_equipment_fragment'][str(_type)]['name']
        else:
            name = '活动文案不存在'
        price = 100
        tmp = {}
        tmp['value'] = "Lv." + str(_lv) + " " + name
        tmp['id'] = int(key)
        tmp['price'] = price
        result_data[33].append(tmp)
        if 33 not in item_name_list:
            item_name_list[33] = {}
        item_name_list[33][key] = "Lv." + str(_lv) + " " + name

    # card_medal
    result_data[84] = []
    for i in game_data['game_card_medal']:
        if i in doc_data['doc_card_medal']:
            name = doc_data['doc_card_medal'][str(i)]['name']
        else:
            name = '活动文案不存在'
        price = 100
        tmp = {}
        tmp['value'] = name + '-' + str(i)
        tmp['id'] = int(i)
        tmp['price'] = price
        result_data[84].append(tmp)
        if 84 not in item_name_list:
            item_name_list[84] = {}
        item_name_list[84][i] = name + '-' + str(i)

    # 主城皮肤碎片
    result_data[107] = []
    for i in game_data['game_city_skin_piece']:
        if i in doc_data['doc_city_skin_piece']:
            name = doc_data['doc_city_skin_piece'][str(i)]['name']
        else:
            name = '活动文案不存在'
        price = 100
        tmp = {}
        tmp['value'] = name + '-' + str(i)
        tmp['id'] = int(i)
        tmp['price'] = price
        result_data[107].append(tmp)
        if 107 not in item_name_list:
            item_name_list[107] = {}
        item_name_list[107][i] = name + '-' + str(i)

    # 治安官皮肤碎片
    result_data[121] = []
    for i in game_data['game_sheriff_skin_piece']:
        if i in doc_data['doc_sheriff_skin_piece']:
            name = doc_data['doc_sheriff_skin_piece'][str(i)]['name']
        else:
            name = '活动文案不存在'
        price = 100
        tmp = {}
        tmp['value'] = name + '-' + str(i)
        tmp['id'] = int(i)
        tmp['price'] = price
        result_data[121].append(tmp)
        if 121 not in item_name_list:
            item_name_list[121] = {}
        item_name_list[121][i] = name + '-' + str(i)

    # 行军皮肤碎片
    result_data[122] = []
    for i in game_data['game_march_skin_piece']:
        if i in doc_data['doc_march_skin_piece']:
            name = doc_data['doc_march_skin_piece'][str(i)]['name']
        else:
            name = '活动文案不存在'
        price = 100
        tmp = {}
        tmp['value'] = name + '-' + str(i)
        tmp['id'] = int(i)
        tmp['price'] = price
        result_data[122].append(tmp)
        if 122 not in item_name_list:
            item_name_list[122] = {}
        item_name_list[122][i] = name + '-' + str(i)

    # 采集皮肤碎片
    result_data[123] = []
    for i in game_data['game_gather_skin_piece']:
        if i in doc_data['doc_gather_skin_piece']:
            name = doc_data['doc_gather_skin_piece'][str(i)]['name']
        else:
            name = '活动文案不存在'
        price = 100
        tmp = {}
        tmp['value'] = name + '-' + str(i)
        tmp['id'] = int(i)
        tmp['price'] = price
        result_data[123].append(tmp)
        if 123 not in item_name_list:
            item_name_list[123] = {}
        item_name_list[123][i] = name + '-' + str(i)

    # 头像框碎片
    result_data[127] = []
    for i in game_data['game_head_frame_piece']:
        if i in doc_data['doc_avatar_frame_piece']:
            name = doc_data['doc_avatar_frame_piece'][str(i)]['name']
        else:
            name = '活动文案不存在'
        price = 100
        tmp = {}
        tmp['value'] = name + '-' + str(i)
        tmp['id'] = int(i)
        tmp['price'] = price
        result_data[127].append(tmp)
        if 127 not in item_name_list:
            item_name_list[127] = {}
        item_name_list[127][i] = name + '-' + str(i)

    # 宝物
    result_data[143] = []
    for i in game_data['game_treasure']:
        if i in doc_data['doc_treasure']:
            name = doc_data['doc_treasure'][str(i)]['name']
        else:
            name = '活动文案不存在'
        price = 100
        tmp = {}
        tmp['value'] = name + '-' + str(i)
        tmp['id'] = int(i)
        tmp['price'] = price
        result_data[143].append(tmp)
        if 143 not in item_name_list:
            item_name_list[143] = {}
        item_name_list[143][i] = name + '-' + str(i)

    # 资源
    result_data[3] = []
    for id in doc_data['doc_resource']:
        if id in doc_data['doc_resource']:
            name = doc_data['doc_resource'][id]['name']
        else:
            name = '活动文案不存在'
        price = 100
        tmp = {}
        tmp['value'] = name + '-' + str(i)
        tmp['id'] = int(id)
        tmp['price'] = price
        result_data[3].append(tmp)
        if 3 not in item_name_list:
            item_name_list[3] = {}
        item_name_list[3][id] = name + '-' + str(i)

    # buff
    result_data[109] = []
    for i in doc_data['doc_buff_info']:
        # id = doc_data['doc_buff_info'][i]['id']
        name = doc_data['doc_buff_info'][i]['name']
        price = 100
        tmp = {}
        tmp['value'] = name + '-' + str(i)
        tmp['id'] = int(i)
        tmp['price'] = price
        result_data[109].append(tmp)
        if 109 not in item_name_list:
            item_name_list[109] = {}
        item_name_list[109][i] = name + '-' + str(i)

    # 勋章
    _id = 165
    result_data[_id] = []
    if 'game_medal_new' in game_data:
        for i in game_data['game_medal_new']:
            if i in doc_data['doc_badge']:
                name = doc_data['doc_badge'][str(i)]['name']
            else:
                name = '活动文案不存在'
            price = 100
            tmp = {}
            tmp['value'] = name + '-' + str(i)
            tmp['id'] = int(i)
            tmp['price'] = price
            result_data[_id].append(tmp)
            if _id not in item_name_list:
                item_name_list[_id] = {}
            item_name_list[_id][i] = name + '-' + str(i)
    # 勋章碎片
    _id = 166
    result_data[_id] = []
    if 'game_medal_piece_new' in game_data:
        for i in game_data['game_medal_piece_new']:
            if i in doc_data['doc_badge_piece']:
                name = doc_data['doc_badge_piece'][str(i)]['name']
            else:
                name = '活动文案不存在'
            price = 100
            tmp = {}
            tmp['value'] = name + '-' + str(i)
            tmp['id'] = int(i)
            tmp['price'] = price
            result_data[_id].append(tmp)
            if _id not in item_name_list:
                item_name_list[_id] = {}
            item_name_list[_id][i] = name + '-' + str(i)
    # 教官
    _id = 167
    result_data[_id] = []
    if 'game_instructor' in game_data:
        for i in game_data['game_instructor']:
            if i in doc_data['doc_instructor_card']:
                name = doc_data['doc_instructor_card'][str(i)]['name']
            else:
                name = '活动文案不存在'
            price = 100
            tmp = {}
            tmp['value'] = name + '-' + str(i)
            tmp['id'] = int(i)
            tmp['price'] = price
            result_data[_id].append(tmp)
            if _id not in item_name_list:
                item_name_list[_id] = {}
            item_name_list[_id][i] = name + '-' + str(i)

    # 教官碎片
    _id = 168
    result_data[_id] = []
    if 'game_instructor_piece' in game_data:
        for i in game_data['game_instructor_piece']:
            if i in doc_data['doc_instructor_piece']:
                name = doc_data['doc_instructor_piece'][str(i)]['name']
            else:
                name = '活动文案不存在'
            price = 100
            tmp = {}
            tmp['value'] = name + '-' + str(i)
            tmp['id'] = int(i)
            tmp['price'] = price
            result_data[_id].append(tmp)
            if _id not in item_name_list:
                item_name_list[_id] = {}
            item_name_list[_id][i] = name + '-' + str(i)

    # z_token
    _id = 177
    result_data[_id] = []
    if 'game_z_token' in game_data:
        for i in game_data['game_z_token']:
            if 'doc_z_token' in doc_data:
                if i in doc_data['doc_z_token']:
                    name = doc_data['doc_z_token'][str(i)]['name']
                else:
                    name = '活动文案不存在'
            else:
                name = '活动文案不存在'
            price = 1
            tmp = {}
            tmp['value'] = name + '-' + str(i)
            tmp['id'] = int(i)
            tmp['price'] = price
            result_data[_id].append(tmp)
            if _id not in item_name_list:
                item_name_list[_id] = {}
            item_name_list[_id][i] = name + '-' + str(i)

    result = {}
    result['reward'] = result_data
    result['name'] = item_name_list

    return result


def loadEquip():
    data = {}
    with open(GLOBAL_PATH + 'equip.json', encoding='utf8') as f:
        data = json.load(f)
    return data

def loadDocument():
    data = {}
    with open(GLOBAL_PATH + 'document_english.json', encoding='utf8') as f:
        data = json.load(f)
    return data

def loadGame():
    data = {}
    with open(GLOBAL_PATH + 'game.json', encoding='utf8') as f:
        data = json.load(f)
    return data

def loadSubGame():
    data = {}
    with open(GLOBAL_PATH + 'sub_game.json', encoding='utf8') as f:
        data = json.load(f)
    return data

def loadDynamicSubGame():
    data = {}
    with open(GLOBAL_PATH + 'dynamic_sub_game.json', encoding='utf8') as f:
        data = json.load(f)
    return data

# def loadSubDoc():
#     data = {}
#     with open(GLOBAL_PATH + 'sub_document_english.json', encoding='utf8') as f:
#         data = json.load(f)
#     return data

def RewardShowToDoc(reward_list,reward_item_list = []):
    if len(reward_item_list) == 0:
        reward_item_list = rewardList()
        reward_item_list = reward_item_list['name']
    result_bonus = []
    for x in range(len(reward_list)):
        item_type = reward_list[x]['a'][0]
        item_id = reward_list[x]['a'][1]
        item_num = reward_list[x]['a'][2]
        item_price = 100
        if item_type in reward_item_list and str(item_id) in reward_item_list[item_type]:
            item_name = reward_item_list[item_type][str(item_id)]
        else:
            item_name = 'ERROR'
        tmp = {"type":item_type,"id":item_id,"num":item_num,"price":item_price,"name":item_name}
        result_bonus.append(tmp)
    return result_bonus


def RewardToTMysqlNew(reward_list):
    result_data = []
    if len(reward_list) > 0:
        for x in range(len(reward_list)):
            data = reward_list[x]
            item_type = int(data['type'])
            item_id = int(data['id'])
            item_num = int(data['num'])
            tmp = {}
            tmp['a'] = [item_type, item_id, item_num]
            result_data.append(tmp)
    return result_data

def RewardToTMysqlDuelYard(reward_list, event_name='duel_yard'):
    """
    用于打子弹和储值活动的奖励格式
    """
    result_data = []
    if event_name == 'duel_yard':
        if len(reward_list) > 0:
            for x in range(len(reward_list)):
                data = reward_list[x]
                item_type = int(data['type'])
                item_id = int(data['id'])
                item_num = int(data['num'])
                item_lv = int(data['lv'])
                tmp = {'a': [item_type, item_id, item_num],
                       'lv': item_lv}
                result_data.append(tmp)

    elif event_name == 'store':
        if len(reward_list) > 0:
            for x in range(len(reward_list)):
                data = reward_list[x]
                item_type = int(data['type'])
                item_id = int(data['id'])
                item_num = int(data['num'])
                item_lv = int(data['lv'])
                tmp = {'a': [item_type, item_id, item_num],
                       'h': item_lv}
                result_data.append(tmp)

    return result_data


def rewardNameId():
    reward = rewardList()
    result = {}
    for type_id in reward['name']:
        data = reward['name'][type_id]
        for idx in data:
            name = data[idx]
            result[name] = idx
    return result


def RewardToTMysql(reward_list, pos=0):

    reward_list = reward_list[str(pos)]['reward']
    sql_data = []
    for x in range(len(reward_list)):
        data = reward_list[x]
        item_type = int(data['type'])
        item_id = int(data['id'])
        item_num = int(data['num'])
        tmp = {}
        tmp['a'] = [item_type, item_id, item_num]

        sql_data.append(tmp)
    return sql_data


def score_type_list():
    with open(STATIC_PATH + 'strongest_sheriff_score_type_list.json', encoding='utf8') as f:
        data = json.load(f)
    result = {}
    task_type_list = data['type_list']
    result['task_type_list'] = data['type_list']
    detail_type_list = {}
    for x in range(len(task_type_list)):
        _type = str(task_type_list[x]['value'])
        id_list = task_type_list[x]['id_list']
        if _type not in detail_type_list:
            detail_type_list[_type] = []

        if id_list == 'chest':
            doc_content = loadDocument()
            sub_game_content = loadSubGame()
            if 'sub_game_chest_get_score_config' in sub_game_content:
                chest_id_list = sub_game_content['sub_game_chest_get_score_config']['chest_id_list']
                for chest_id in chest_id_list:
                    if str(chest_id) in doc_content['doc_item']:
                        detail_type_list[_type].append({
                            'value': chest_id,
                            'label': doc_content['doc_item'][str(chest_id)]['name']
                            })
                    else:
                        detail_type_list[_type].append({
                            'value': chest_id,
                            'label': 'chest error {0}'.format(chest_id)
                            })
        else:
            detail_type_list[_type] = data[id_list]
    result['detail_type_list'] = detail_type_list

    result['doc_id_list'] = []
    doc_data = loadDocument()
    for i in doc_data['doc_scoring_rule']:
        result['doc_id_list'].append(
            {"label": doc_data['doc_scoring_rule'][i]['content'], "value": int(i)})

    return result

def task_bp_score_type_list():
    with open(STATIC_PATH + 'task_bp_card_type_list.json', encoding='utf8') as f:
        data = json.load(f)
    return data

def score_bp_score_type_list():
    with open(STATIC_PATH + 'score_bp_card_type_list.json', encoding='utf8') as f:
        data = json.load(f)
    return data


def UpdateRankGoalReward(bonus_list, type):
    reward_data = []
    for idx in bonus_list:
        data = bonus_list[idx]
        if type == 0:
            _from = 1
        else:
            _from = int(data['from'])
        _to = int(data['to'])
        reward = []
        for r_idx in range(len(data['reward'])):
            item_type = int(data['reward'][r_idx]['type'])
            item_id = int(data['reward'][r_idx]['id'])
            item_num = int(data['reward'][r_idx]['num'])
            tmp = {}
            tmp['a'] = [item_type, item_id, item_num]
            reward.append(tmp)
        reward_data.append({"from": _from, "to": _to, "reward": reward})
    return reward_data


def RankGoalReward(bonus_list, reward_item_list=[]):
    if len(reward_item_list) == 0:
        reward_item_list = rewardList()
        reward_item_list = reward_item_list['name']
    result_bonus = {}
    item_pos = 0
    if len(bonus_list) > 0:
        for idx in range(len(bonus_list)):
            _from = bonus_list[idx]['from']
            _to = bonus_list[idx]['to']
            reward_data = bonus_list[idx]['reward']
            for i in range(len(reward_data)):
                item_type = reward_data[i]['a'][0]
                item_id = reward_data[i]['a'][1]
                item_num = reward_data[i]['a'][2]
                item_rate = 1
                item_price = 100
                item_pos = idx
                if item_type in reward_item_list and str(item_id) in reward_item_list[item_type]:
                    item_name = reward_item_list[item_type][str(item_id)]
                else:
                    item_name = 'ERROR'
                if item_pos not in result_bonus:
                    result_bonus[item_pos] = {}
                    result_bonus[item_pos]['from'] = _from
                    result_bonus[item_pos]['to'] = _to
                    result_bonus[item_pos]['reward'] = []
                tmp = {"type": item_type, "id": item_id, "num": item_num, "rate": item_rate,
                       "price": item_price, "pos": item_pos, "name": item_name, "from": _from, "to": _to}
                result_bonus[item_pos]['reward'].append(tmp)
    else:
        if item_pos not in result_bonus:
            result_bonus[item_pos] = {}
            result_bonus[item_pos]['from'] = 1
            result_bonus[item_pos]['to'] = 1
            result_bonus[item_pos]['reward'] = []

    result = {'bonus': result_bonus}
    return result


def BattleGoalReward(bonus_list, reward):
    reward = reward['name']
    result_bonus = {}
    item_pos = 0
    if len(bonus_list) > 0:
        for idx in range(len(bonus_list)):
            show_lv = bonus_list[idx]['show_lv']
            special_lv = bonus_list[idx]['special_lv']
            status = bonus_list[idx]['status']
            if 'resbox' in bonus_list[idx]:
                resbox = bonus_list[idx]['resbox']
            else:
                resbox = ''
            reward_data = bonus_list[idx]['reward']
            for i in range(len(reward_data)):
                item_type = reward_data[i]['a'][0]
                item_id = reward_data[i]['a'][1]
                item_num = reward_data[i]['a'][2]
                item_rate = 1
                item_price = 100
                item_pos = idx
                if item_type in reward and str(item_id) in reward[item_type]:
                    item_name = reward[item_type][str(item_id)]
                else:
                    item_name = 'ERROR'
                if item_pos not in result_bonus:
                    result_bonus[item_pos] = {}
                    result_bonus[item_pos]['show_lv'] = show_lv
                    result_bonus[item_pos]['special_lv'] = special_lv
                    result_bonus[item_pos]['status'] = status
                    result_bonus[item_pos]['resbox'] = resbox
                    result_bonus[item_pos]['reward'] = []
                tmp = {"type": item_type, "id": item_id, "num": item_num, "rate": item_rate, "price": item_price, "pos": item_pos,
                       "name": item_name, "show_lv": show_lv, "special_lv": special_lv, "status": status, 'resbox': resbox}
                result_bonus[item_pos]['reward'].append(tmp)
    else:
        if item_pos not in result_bonus:
            result_bonus[item_pos] = {}
            result_bonus[item_pos]['show_lv'] = 1
            result_bonus[item_pos]['special_lv'] = 1
            result_bonus[item_pos]['status'] = 0
            result_bonus[item_pos]['resbox'] = ''
            result_bonus[item_pos]['reward'] = []

    result = {'bonus': result_bonus}
    return result


def UpdateBattleGoalReward(bonus_list):
    reward_data = []
    for idx in bonus_list:
        data = bonus_list[idx]
        show_lv = int(data['show_lv'])
        special_lv = int(data['special_lv'])
        # status = int(data['status'])
        status = 0
        reward = []
        for r_idx in range(len(data['reward'])):
            item_type = int(data['reward'][r_idx]['type'])
            item_id = int(data['reward'][r_idx]['id'])
            item_num = int(data['reward'][r_idx]['num'])
            tmp = {}
            tmp['a'] = [item_type, item_id, item_num]
            reward.append(tmp)
        if 'resbox' in data:
            reward_data.append({"show_lv": show_lv, "special_lv": special_lv,
                                "status": status, "reward": reward, 'resbox': data['resbox']})
        else:
            reward_data.append({"show_lv": show_lv, "special_lv": special_lv,
                                "status": status, "reward": reward, 'resbox': ''})
    return reward_data


def loadPayLevel():
    data = {}
    with open(STATIC_PATH + 'pay_level.json', encoding='utf8') as f:
        data = json.load(f)
    return data

def GetBuildingIdList():
    data = {}
    with open(STATIC_PATH + 'building_id_list.json', encoding='utf-8') as f:
        data = json.load(f)
    return data

def DownLoad(filename, result_data, is_push=0, evn=EVN):

    cur_time = int(time.time())
    new_filename = filename + "_" + str(cur_time) + ".json"

    current_dir = os.path.dirname(os.path.realpath(__file__)) + "/tmp_data"
    fh = open(current_dir+"/"+new_filename, "w")
    json.dump(result_data, fh, sort_keys=True, separators=(',', ':'))
    fh.close()
    if is_push == 0:
        response = make_response(
            send_from_directory(current_dir, new_filename.encode('utf-8').decode('utf-8'), as_attachment=True))
        response.headers["Content-Disposition"] = "attachment; filename={}".format(
            new_filename.encode().decode('latin-1'))
        response.headers["Cache-Control"] = "no-cache"
        response.headers["max-age"] = 0
        return response
    else:
        s3_bucket_list = {}
        with open(STATIC_PATH + 's3_bucket_list.json', encoding='utf8') as f:
            s3_bucket_list = json.load(f)
        if filename not in s3_bucket_list:
            s3_bucket = s3_bucket_list['public']['s3_bucket']
            s3_key = s3_bucket_list['public'][evn] + filename + '.json.ok'
        else:
            s3_bucket = s3_bucket_list[filename]['s3_bucket']
            s3_key = s3_bucket_list[filename][evn] + filename + '.json.ok'
        response = s3_client.upload_file(
            './controllers/tmp_data/'+new_filename, s3_bucket, s3_key)

        if filename not in s3_bucket_list:
            s3_key = s3_bucket_list['public'][evn] + filename + '.json'
            response = s3_client.upload_file(
                './controllers/tmp_data/'+new_filename, s3_bucket, s3_key)
        else:
            s3_key = s3_bucket_list[filename][evn] + filename + '.json'
            response = s3_client.upload_file(
                './controllers/tmp_data/'+new_filename, s3_bucket, s3_key)

            # 20220721 走新发布系统，不用post
            # if 'publish' in s3_bucket_list[filename]:
            #     push_to_env(filename)

        if 'publish_schedule' in s3_key:
            return_data = push_to_env(filename)

        # return_data = push_to_env(filename)

        return jsonify({"msg": "发布成功", "ret": 1})
    return False


def DownLoad_get_md5(filename, result_data, is_push=0, evn=EVN):

    cur_time = int(time.time())
    new_filename = filename + "_" + str(cur_time) + ".json"

    current_dir = os.path.dirname(os.path.realpath(__file__)) + "/tmp_data"
    full_file_path = f"{current_dir}/{new_filename}"
    fh = open(full_file_path, "w")
    json.dump(result_data, fh, sort_keys=True, separators=(',', ':'))
    fh.close()
    if is_push == 0:
        response = make_response(
            send_from_directory(current_dir, new_filename.encode('utf-8').decode('utf-8'), as_attachment=True))
        response.headers["Content-Disposition"] = "attachment; filename={}".format(
            new_filename.encode().decode('latin-1'))
        response.headers["Cache-Control"] = "no-cache"
        response.headers["max-age"] = 0
        return response
    else:
        file_md5 = get_md5(full_file_path)
        s3_bucket_list = {}
        with open(STATIC_PATH + 's3_bucket_list.json', encoding='utf8') as f:
            s3_bucket_list = json.load(f)
        if filename not in s3_bucket_list:
            s3_bucket = s3_bucket_list['public']['s3_bucket']
            s3_key = s3_bucket_list['public'][evn] + filename + '.json.ok'
        else:
            s3_bucket = s3_bucket_list[filename]['s3_bucket']
            s3_key = s3_bucket_list[filename][evn] + filename + '.json.ok'
        response = s3_client.upload_file(
            './controllers/tmp_data/'+new_filename, s3_bucket, s3_key)

        if filename not in s3_bucket_list:
            s3_key = s3_bucket_list['public'][evn] + filename + '.json'
            response = s3_client.upload_file(
                './controllers/tmp_data/'+new_filename, s3_bucket, s3_key)
        else:
            s3_key = s3_bucket_list[filename][evn] + filename + '.json'
            response = s3_client.upload_file(
                './controllers/tmp_data/'+new_filename, s3_bucket, s3_key)

            # 20220721 走新发布系统，不用post
            # if 'publish' in s3_bucket_list[filename]:
            #     push_to_env(filename)

        if 'publish_schedule' in s3_key:
            return_data = push_to_env(filename)

        # return_data = push_to_env(filename)

        return file_md5
    return False


def read_s3_file(filename):
    s3_bucket_list = {}
    with open(STATIC_PATH + 's3_bucket_list.json', encoding='utf8') as f:
        s3_bucket_list = json.load(f)
    if filename not in s3_bucket_list:
        s3_bucket = s3_bucket_list['public']['s3_bucket']
        s3_key = s3_bucket_list['public'][EVN] + filename + '.json'
    else:
        s3_bucket = s3_bucket_list[filename]['s3_bucket']
        s3_key = s3_bucket_list[filename][EVN] + filename + ".json"
    data = s3_client.read_s3_file(s3_bucket, s3_key)
    return data

def dealKvkOldScoreDoc(score_node, doc_node):
    with open(STATIC_PATH + 'kvk_event_old_resource_name.json', encoding='utf-8') as f:
        old_resource_name_list = json.load(f)

    division = score_node['division']
    score_id_map = score_node['score_id_map']

    new_doc_node = deepcopy(doc_node)

    for k, v in new_doc_node.items():
        v = v.replace('STRING0', str(division))

        if 'STRING1' in v:
            for map_k in score_id_map.keys():
                troop_lv = map_k

            v = v.replace('STRING1', troop_lv)

        elif 'STRING2' in v:
            if '1' in score_id_map:
                v = v.replace('STRING2', old_resource_name_list['1'][k])
            elif '2' in score_id_map:
                v = v.replace('STRING2', old_resource_name_list['2'][k])
            elif '3' in score_id_map:
                v = v.replace('STRING2', old_resource_name_list['3'][k])
            elif '4' in score_id_map:
                v = v.replace('STRING2', old_resource_name_list['4'][k])
            elif '0' in score_id_map:
                v = v.replace('STRING2', old_resource_name_list['0'][k])

        new_doc_node[k] = v

    return new_doc_node

def GetDocByFilename(field):
    with open(GLOBAL_PATH + 'operation_event_english.json', encoding='utf8') as f:
        data = json.load(f)
    if field in data:
        return data[field]
    else:
        return {}

def GetDocByFilenameNew(field):
    with open(GLOBAL_PATH + 'operation_event_english.json', encoding='utf8') as f:
        data = json.load(f)
    result = []
    if field in data:
        for k, v in data[field].items():
            result.append({
                'value': int(k),
                'label': '{0}-{1}'.format(k, v['title'])
            })
    else:
        result.append({'value': 1, 'label': '1-文案表不存在'})

    return result


def GetNewOperationEventList(doc_node, field):
    result = []
    with open(GLOBAL_PATH + 'new_operation_event.json', encoding='utf-8') as f:
        operation_file = json.load(f)
    if doc_node in operation_file:
        for i in operation_file[doc_node]:
            if '0' in operation_file[doc_node][i]:
                if field in operation_file[doc_node][i]['0']:
                    result.append({
                        'value': int(i),
                        'label': f'{int(i)} - {operation_file[doc_node][i]["0"][field]}'
                    })
    return result

def getCoinExpireFile():
    with open(AUTO_SCHEDULE_PATH + 'coin_expired.json', encoding='utf-8') as f:
        content = json.load(f)
    return content

def saveCoinExpireFile(data):
    with open(AUTO_SCHEDULE_PATH + 'coin_expired.json', 'w', encoding='utf-8') as f:
        f.write(json.dumps(data))
    DownLoad('coin_expired', data, is_push=1, evn=EVN)

def genCionExpiredJson(data):
    """
    目前只有兑换商城的排期和方案在一起 做特殊处理
    data = {
        'proj': {$pid: {...}},
        'schedule': {$store_type: [...]}}
    """
    sub_game_token = loadSubGame()['sub_game_token']
    content = {}
    schedule = data['schedule']
    proj = data['proj']

    for sch_list in schedule.values():
        for node in sch_list:
            pid = node['pid']
            end_time = node['end_time']

            currency = proj[str(pid)]['currency']
            goods = proj[str(pid)]['goods'][0]

            for coin_node in currency:
                if coin_node[0] == 117:
                    coin_id = coin_node[1]
                    if str(coin_id) in sub_game_token and sub_game_token[str(coin_id)]['type'] == 2:
                        if str(coin_id) not in content:
                            content[str(coin_id)] = end_time
                        else:
                            if end_time > content[str(coin_id)]:
                                content[str(coin_id)] = end_time

            for good in goods:
                coin_list = good[-1]
                for coin_node in coin_list:
                    coin_type = coin_node['a'][0]
                    coin_id = coin_node['a'][1]
                    if coin_type == 117:
                        if str(coin_id) in sub_game_token and sub_game_token[str(coin_id)]['type'] == 2:
                            if str(coin_id) not in content:
                                content[str(coin_id)] = end_time
                            else:
                                if end_time > content[str(coin_id)]:
                                    content[str(coin_id)] = end_time

    DownLoad('coin_expired_shop', content, is_push=1, evn=EVN)
    coin_expired_cw = read_s3_file('coin_expired_cw')
    coin_expired_iron = read_s3_file('coin_expired_iron')
    coin_expired_cake = read_s3_file('coin_expired_cake')
    coin_expired_shop = read_s3_file('coin_expired_shop')
    coin_expired_conquest = read_s3_file('coin_expired_conquest')
    total_data = {}
    for node in [coin_expired_cw, coin_expired_iron,
                 coin_expired_cake, coin_expired_shop,
                 coin_expired_conquest]:
        for k, v in node.items():
            if k not in total_data:
                total_data[k] = v
            else:
                total_data[k] =max(total_data[k], v)
    DownLoad('coin_expired', total_data, is_push=1, evn=EVN)

def getIapList(_type):
    """
    _type = 1: [{'value': gem, 'label': '$label-$gem'}],
    _type = 2: {gem: price}
    """
    result = []
    with open(STATIC_PATH + 'iap_list.json', encoding='utf-8') as f:
        content = json.load(f)
    if _type == 1:
        for node in content:
            result.append({
                'value': node['gem'],
                'label': f'${node["label"]}-{node["gem"]}'
                })
    elif _type == 2:
        result = {}
        for node in content:
            result[node['gem']] = node['iap']

    return result


def get_doc_id_list(node_name, field_name):
    result = []
    with open(GLOBAL_PATH + 'new_operation_event.json', encoding='utf-8') as f:
        operation_file = json.load(f)

    if node_name in operation_file:
        for i in operation_file[node_name]:
            if '0' in operation_file[node_name][i]:  # en
                if field_name in operation_file[node_name][i]['0']:
                    result.append({
                        'value': int(i),
                        'label': f'{int(i)} - {operation_file[node_name][i]["0"][field_name]}'
                    })
    return result


def SafeToSidList(str_sid):
    try:
        data = []
        if str(str_sid) == '-1' or str(str_sid) == '-1.0':
            return True, [-1]
        sid_list = str_sid.split(',')
        for i in range(len(sid_list)):
            sid = sid_list[i]
            if sid == '':
                continue
            if '-' in sid and str(sid) != '-1':
                tmp_sid = sid.split('-')
                for j in range(int(tmp_sid[0]),int(tmp_sid[1])+1):
                    data.append(j)
            else:
                data.append(int(float(sid)))
        return True, list(set(data))
    except Exception as e:
        logging.exception(e)
        return False, []


def get_doc_id_list_in_operation_event_english(evnet_key, field, no_label=False):
    status = 'success'
    result = []
    try:
        with open(GLOBAL_PATH + 'operation_event_english.json', encoding="UTF-8") as f:
            operation_event_english_data = json.load(f)
    except Exception as e:
        logging.exception(e)
        operation_event_english_data = {}
        status = 'open_file_fail'

    if evnet_key in operation_event_english_data:
        for doc_id in operation_event_english_data[evnet_key]:
            if field in operation_event_english_data[evnet_key][doc_id]:
                if no_label:
                    label = f"{doc_id}"
                else:
                    label = f"{doc_id} - {operation_event_english_data[evnet_key][doc_id][field]}"
                result.append({
                    'value': int(doc_id),
                    'label': label
                })
    else:
        if status == 'success':
            status = 'key_not_in_file'

    if len(result) <= 0 and status == 'success':
        status = 'doc_id_list_empty'
    return {
        'status': status,
        'doc_id_list': result
    }


def get_md5(file_path):
    hash_md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()


def get_static_config_file(file_name):
    file_data = {}
    try:
        with open(f"{STATIC_PATH}{file_name}.json", encoding='utf-8') as f:
            file_data = json.load(f)
    except Exception as e:
        logging.exception(e)
    return file_data


def get_file_compare_config(event_name):
    result = {}
    config_data = get_static_config_file('event_compare_config')
    if event_name in config_data:
        result = config_data[event_name]
    return result


def get_file_compare_md5_default_object(event_name):
    config_data = get_file_compare_config(event_name)
    result = {}
    if 'file_list' in config_data:
        for i in config_data['file_list']:
            result[i] = ""
    else:
        raise Exception(f"[File Compare] [event_name={event_name}] get event config file_list error: file_list is undefined")

    return result


def get_current_timestamp():
    return int(time.time())
